<!DOCTYPE html>



  


<html class="theme-next mist use-motion" lang="zh-Hans">
<head>
  <!-- hexo-inject:begin --><!-- hexo-inject:end --><meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="Python," />





  <link rel="alternate" href="/atom.xml" title="飞奔的弹幕君" type="application/atom+xml" />






<meta name="description" content="1. python里args和*kwargs的用法引入参数*args和**kwargs，两个都是python中的可变参数。*args表示任何多个无名参数，它是一个tuple**kwargs表示关键字参数，它是一个dict。并且同时使用*args和**kwargs时，必须*args参数列要在**kwargs前12345678910def foo(*args, **kwargs):    print">
<meta name="keywords" content="Python">
<meta property="og:type" content="article">
<meta property="og:title" content="python学习笔记(1)">
<meta property="og:url" content="https://2033329616.github.io/python学习笔记.html">
<meta property="og:site_name" content="飞奔的弹幕君">
<meta property="og:description" content="1. python里args和*kwargs的用法引入参数*args和**kwargs，两个都是python中的可变参数。*args表示任何多个无名参数，它是一个tuple**kwargs表示关键字参数，它是一个dict。并且同时使用*args和**kwargs时，必须*args参数列要在**kwargs前12345678910def foo(*args, **kwargs):    print">
<meta property="og:locale" content="zh-Hans">
<meta property="og:updated_time" content="2018-06-29T14:33:09.785Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="python学习笔记(1)">
<meta name="twitter:description" content="1. python里args和*kwargs的用法引入参数*args和**kwargs，两个都是python中的可变参数。*args表示任何多个无名参数，它是一个tuple**kwargs表示关键字参数，它是一个dict。并且同时使用*args和**kwargs时，必须*args参数列要在**kwargs前12345678910def foo(*args, **kwargs):    print">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Mist',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://2033329616.github.io/python学习笔记.html"/>





  <title>python学习笔记(1) | 飞奔的弹幕君</title>
  





  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?1c22fa11e6aaf2d164ec822eab4601b2";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script><!-- hexo-inject:begin --><!-- hexo-inject:end -->




</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <!-- hexo-inject:begin --><!-- hexo-inject:end --><div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">飞奔的弹幕君</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off"
             placeholder="搜索..." spellcheck="false"
             type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://2033329616.github.io/python学习笔记.html">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="David">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/avatar.png">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="飞奔的弹幕君">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">python学习笔记(1)</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2018-04-20T20:49:59+08:00">
                2018-04-20
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/Python/" itemprop="url" rel="index">
                    <span itemprop="name">Python</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          
             <span id="/python学习笔记.html" class="leancloud_visitors" data-flag-title="python学习笔记(1)">
               <span class="post-meta-divider">|</span>
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               
                 <span class="post-meta-item-text">阅读次数&#58;</span>
               
                 <span class="leancloud-visitors-count"></span>
             </span>
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h3 id="1-python里args和-kwargs的用法"><a href="#1-python里args和-kwargs的用法" class="headerlink" title="1. python里args和*kwargs的用法"></a>1. python里<em>args和*</em>kwargs的用法</h3><p><code>引入参数*args和**kwargs，两个都是python中的可变参数。*args表示任何多个无名参数，它是一个tuple</code><br><code>**kwargs表示关键字参数，它是一个dict。并且同时使用*args和**kwargs时，必须*args参数列要在**kwargs前</code><br><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">foo</span><span class="params">(*args, **kwargs)</span>:</span></span><br><span class="line">    <span class="keyword">print</span> <span class="string">'args = '</span>, args</span><br><span class="line">    <span class="keyword">print</span> <span class="string">'kwargs = '</span>, kwargs</span><br><span class="line">    <span class="keyword">print</span> <span class="string">'---------------------------------------'</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">if</span> __name__ == <span class="string">'__main__'</span>:</span><br><span class="line">    foo(<span class="number">1</span>,<span class="number">2</span>,<span class="number">3</span>,<span class="number">4</span>)                             <span class="comment">#参数只传到*args中</span></span><br><span class="line">    foo(a=<span class="number">1</span>,b=<span class="number">2</span>,c=<span class="number">3</span>)                         <span class="comment">#参数只传到**kwargs中</span></span><br><span class="line">    foo(<span class="number">1</span>,<span class="number">2</span>,<span class="number">3</span>,<span class="number">4</span>, a=<span class="number">1</span>,b=<span class="number">2</span>,c=<span class="number">3</span>)                <span class="comment">#参数可以传到*args和**kwargs中</span></span><br><span class="line">    foo(<span class="string">'a'</span>, <span class="number">1</span>, <span class="keyword">None</span>, a=<span class="number">1</span>, b=<span class="string">'2'</span>, c=<span class="number">3</span>)</span><br></pre></td></tr></table></figure></p>
<p>运行结果：<br><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">args =  (<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>, <span class="number">4</span>)</span><br><span class="line">kwargs =  &#123;&#125;</span><br><span class="line">---------------------------------------</span><br><span class="line">args =  ()</span><br><span class="line">kwargs =  &#123;<span class="string">'a'</span>: <span class="number">1</span>, <span class="string">'c'</span>: <span class="number">3</span>, <span class="string">'b'</span>: <span class="number">2</span>&#125;</span><br><span class="line">---------------------------------------</span><br><span class="line">args =  (<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>, <span class="number">4</span>)</span><br><span class="line">kwargs =  &#123;<span class="string">'a'</span>: <span class="number">1</span>, <span class="string">'c'</span>: <span class="number">3</span>, <span class="string">'b'</span>: <span class="number">2</span>&#125;</span><br><span class="line">---------------------------------------</span><br><span class="line">args =  (<span class="string">'a'</span>, <span class="number">1</span>, <span class="keyword">None</span>)</span><br><span class="line">kwargs =  &#123;<span class="string">'a'</span>: <span class="number">1</span>, <span class="string">'c'</span>: <span class="number">3</span>, <span class="string">'b'</span>: <span class="string">'2'</span>&#125;</span><br><span class="line">---------------------------------------</span><br></pre></td></tr></table></figure></p>
<h3 id="2-python对txt文件的操作"><a href="#2-python对txt文件的操作" class="headerlink" title="2.python对txt文件的操作"></a>2.python对txt文件的操作</h3><p>2.1 使用<strong>open()</strong> 函数读取文本内容，本函数是打开一个文件并返回文件对象。如果文件不能打开，抛出异常OSError<br><code>open(file, mode=&#39;r&#39;, buffering=-1, encoding=None, errors=None, newline=None, closefd=T)</code><br>参数mode是指明打开文件的模式。默认值是’r’，表示使用文本的方式打开文件来读取。</p>
<p>‘r’表示打开文件只读，不能写。</p>
<p>‘w’表示打开文件只写，并且清空文件。</p>
<p>‘x’表示独占打开文件，如果文件已经存打开就会失败。</p>
<p>‘a’表示打开文件写，不清空文件，在文件后尾追加的方式写入。</p>
<p>‘b’表示二进制的模式打开文件。</p>
<p>‘t’表示文本模式，默认情况下就是这种模式。</p>
<p>‘+’打开文件更新（读取或写入）。</p>
<p>缺省时的模式就相当于’rt’。比如’w+b’就是打开文件进入读写，把文件清空；’r+b’打开文件，但不把文件清空<br>打开文件的操作常使用异常捕捉来</p>
<p>str.strip(rm)方法,去除字符串开头和结尾的rm字符，<code>readline()</code>获取的是一行文本的字符串形式<br><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">open_file</span><span class="params">(filename)</span>:</span></span><br><span class="line">    <span class="string">"""打开一个文件，存储到列表中，并返回该列表"""</span></span><br><span class="line">    <span class="keyword">try</span>:</span><br><span class="line">        <span class="keyword">with</span> open(filename) <span class="keyword">as</span> file_open:    <span class="comment">#打开文件，因为只有一行，所以不用使用循环</span></span><br><span class="line">            data = file_open.readline()</span><br><span class="line">        <span class="comment"># [james,james2,james3] = data.strip().split(',', 2)          #方法串链，从左向右作用</span></span><br><span class="line">        file_data = data.strip().split(<span class="string">','</span>)</span><br><span class="line">        <span class="string">"""split方法返回字符串列表，如果只是一个标识符接受，则不会报错</span></span><br><span class="line"><span class="string">        如果是[list1,list2,...]的形式则有可能因为接受数据的列表元素个数，与返回的</span></span><br><span class="line"><span class="string">        字符串列表的个数不一致而导致ValueError"""</span></span><br><span class="line">        <span class="keyword">return</span> file_data</span><br><span class="line">    <span class="keyword">except</span> IOError <span class="keyword">as</span> ioerr:</span><br><span class="line">        <span class="keyword">print</span> <span class="string">'IOError:'</span> + str(ioerr)</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">None</span></span><br><span class="line">    <span class="keyword">except</span> ValueError <span class="keyword">as</span> valerr:</span><br><span class="line">        <span class="keyword">print</span> <span class="string">'ValueError:'</span> + str(valerr)</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">None</span></span><br></pre></td></tr></table></figure></p>
<p> <code>(role, line_spoken) = each_line.split(&#39; ,&#39;)</code>，多重赋值(),[]均可以接受数据-字符串列表，<strong>each_line本身不会被分割，保持不变</strong><br><code>[role, line_spoken] = each_line.split(&#39;, &#39;,1)</code><br><code>[string1, string2, string3] = each_line.split(&#39;, &#39;, 2)</code>如果分割后的字符首位有“空格”，也会把其当成字符串第二个参数表示使用的分割符的个数，使用1则分为两个部分，如果不加则表示只要存在分隔符就会分解,n个分隔符分为n+1个部分，空字符也算入被分割的部分</p>
<p>2.2 使用<strong>open()</strong> 函数和<strong>file_object.write()</strong> 方法写入文本<br><strong>方法一、增加额外的逻辑来处理异常</strong>,使用finally来关闭文件对象<br><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">try</span>:   <span class="comment">#文件写入过程</span></span><br><span class="line">    man_file = open(<span class="string">'man_data.txt'</span>, <span class="string">'w'</span>)         <span class="comment">#新建文件</span></span><br><span class="line">    other_file = open(<span class="string">'other_data.txt'</span>, <span class="string">'w'</span>)</span><br><span class="line">    <span class="string">""" write()与print都可以写入数据，当print可以由字符串或列表写入，</span></span><br><span class="line"><span class="string">    write()括号里只能是字符串，所以列表需要先转换后字符串再放到括号里"""</span></span><br><span class="line">    <span class="comment"># print &gt;&gt; man_file, man                       #文件对象里传入数据</span></span><br><span class="line">    <span class="comment"># print &gt;&gt; other_file, other</span></span><br><span class="line">    man_file.write(str(man))</span><br><span class="line">    other_file.write(str(other))</span><br><span class="line"><span class="keyword">except</span> IOError:</span><br><span class="line">    <span class="keyword">print</span> <span class="string">'File error.'</span></span><br><span class="line"><span class="keyword">finally</span>:  <span class="comment">#无论有无异常，此句都会执行，</span></span><br><span class="line">    man_file.close()</span><br><span class="line">    other_file.close()</span><br></pre></td></tr></table></figure></p>
<p><strong>方法二、with处理文件异常</strong>,不用考虑关闭文件对象<br><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">try</span>:   <span class="comment">#文件写入过程</span></span><br><span class="line">    <span class="comment"># with open('man_data.txt', 'w') as man_file:         #新建文件</span></span><br><span class="line">    <span class="comment">#     # print &gt;&gt; man_file, man                        #文件对象里传入数据</span></span><br><span class="line">    <span class="comment">#     man_file.write(str(man))</span></span><br><span class="line">    <span class="comment"># with open('other_data.txt', 'w') as other_file:</span></span><br><span class="line">    <span class="comment">#     """ write()与print都可以写入数据，当print可以由字符串或列表写入，</span></span><br><span class="line">    <span class="comment">#          write()括号里只能是字符串，所以列表需要先转换后字符串再放到括号里"""</span></span><br><span class="line">    <span class="comment">#     # print &gt;&gt; other_file, other</span></span><br><span class="line">    <span class="comment">#     other_file.write(str(other))</span></span><br><span class="line">    <span class="keyword">with</span> open(<span class="string">'man_data.txt'</span>, <span class="string">'w'</span>) <span class="keyword">as</span> man_file, open(<span class="string">'other_data.txt'</span>, <span class="string">'w'</span>) <span class="keyword">as</span> other_file:</span><br><span class="line">        <span class="comment">#两个语句合并为一个with语句</span></span><br><span class="line">        man_file.write(str(man))</span><br><span class="line">        other_file.write(str(other))</span><br><span class="line"><span class="keyword">except</span> IOError <span class="keyword">as</span> err:</span><br><span class="line">    <span class="keyword">print</span> <span class="string">'File error:'</span> + str(err)</span><br></pre></td></tr></table></figure></p>
<p>2.3实例<br>打开train_data.txt，读取其中的前四行，然后存储到train_data2.txt文件里</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># encoding:utf-8</span></span><br><span class="line"><span class="comment"># file.readlines()读取数据的行数，'行数据\n' 是该方法输出列表的每行数据的元素</span></span><br><span class="line">attribute_data = []</span><br><span class="line"><span class="keyword">try</span>:</span><br><span class="line">	<span class="keyword">with</span> open(<span class="string">'./train_data.txt'</span>) <span class="keyword">as</span> file,  open(<span class="string">'./train_data2.txt'</span>,<span class="string">'w'</span>) <span class="keyword">as</span> file2:</span><br><span class="line">		raw_number = len(file.readlines())      <span class="comment"># 计算文件的总行数</span></span><br><span class="line">		file.seek(<span class="number">0</span>)                            <span class="comment"># 回到第一行，因为每次使用readline，文本都会后退一行</span></span><br><span class="line">		<span class="keyword">for</span> i <span class="keyword">in</span> range(raw_number):	        	<span class="comment"># 计算文件的总行数，设计循环逐行读入数据	</span></span><br><span class="line">			text_line = file.readline()     	<span class="comment"># 每次调用该函数使文件下移一行</span></span><br><span class="line">			<span class="comment"># temp_file = text_line.strip().split(' ', 32)              # temp_file存储分割后的数据列表</span></span><br><span class="line">			<span class="comment"># attribute_data = temp_file[0:2] + temp_file[12:32]        # 存储要使用的数据列</span></span><br><span class="line">			temp_file = text_line.strip().split(<span class="string">' '</span>, <span class="number">4</span>)             	<span class="comment"># temp_file存储分割后的数据列表</span></span><br><span class="line">			attribute_data = temp_file[<span class="number">0</span>:<span class="number">4</span>]      <span class="comment"># 存储要使用的数据列</span></span><br><span class="line"></span><br><span class="line">			<span class="keyword">for</span> data <span class="keyword">in</span> attribute_data:          <span class="comment"># 逐行写入数据,只能每个字符分别读入，才可以在数据中间插入空格</span></span><br><span class="line">				file2.writelines(data)</span><br><span class="line">				file2.writelines(<span class="string">' '</span>)            <span class="comment"># 数据间加入空格</span></span><br><span class="line">			file2.writelines(<span class="string">'\n'</span>)               <span class="comment"># 数据换行</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">except</span> IOError <span class="keyword">as</span> err:</span><br><span class="line">    <span class="keyword">print</span> <span class="string">'File error:'</span> + str(err)</span><br><span class="line"><span class="keyword">print</span> attribute_data </span><br><span class="line">`</span><br></pre></td></tr></table></figure>
<h3 id="3-python函数shutil，实现文件的复制"><a href="#3-python函数shutil，实现文件的复制" class="headerlink" title="3.python函数shutil，实现文件的复制"></a>3.python函数shutil，实现文件的复制</h3><p>使用<code>shutil.copy(str_file1,str_file2)</code>将文件str_file1，复制到文件str_file2的位置</p>
<h3 id="4-python实现读取文件夹里文件名功能"><a href="#4-python实现读取文件夹里文件名功能" class="headerlink" title="4.python实现读取文件夹里文件名功能"></a>4.python实现读取文件夹里文件名功能</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> os </span><br><span class="line">path = <span class="string">'the path of the directory'</span>    <span class="comment"># 读取文件路径</span></span><br><span class="line">list_name = os.listdir(path)            <span class="comment"># 读取路径下文件和文件夹的名</span></span><br></pre></td></tr></table></figure>
<p>则list_name就是文件夹里所以子文件夹和文件的列表，可以通过os.path.isfile和os.path.isdir来对列表里的项进行判断看是文件还是文件夹。</p>
<h3 id="5-python新建字典"><a href="#5-python新建字典" class="headerlink" title="5.python新建字典"></a>5.python新建字典</h3><ol>
<li>使用最基础的{ }方法</li>
<li>使用dict()将元素为二元组的列表转换为字典</li>
<li>使用参数赋值法dict(a=1)方式来创建字典，不过key只能为字符即dict(1=3,’1’=4)不行</li>
<li>使用zip处理两个列表<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line">a = &#123;<span class="string">'a'</span>:<span class="number">1</span>, <span class="number">1</span>:<span class="number">2</span>, <span class="number">3</span>:<span class="string">'b'</span>&#125;</span><br><span class="line">print(a)</span><br><span class="line">b  = dict([(<span class="string">'a'</span>,<span class="string">'b'</span>),(<span class="number">1</span>,<span class="number">2</span>),(<span class="number">3</span>,<span class="string">'c'</span>)])</span><br><span class="line">print(b)</span><br><span class="line">c = dict(a=<span class="number">1</span>, b=<span class="number">3</span>)</span><br><span class="line">print(c)</span><br><span class="line">d = dict(zip(<span class="string">'abc'</span>, [<span class="number">1</span>,<span class="number">2</span>,<span class="number">3</span>]))</span><br><span class="line">print(d)</span><br><span class="line">e = dict(zip([<span class="string">'a'</span>, <span class="number">1</span>, <span class="string">'b'</span>], [<span class="number">2</span>, <span class="string">'c'</span>, <span class="number">3</span>]))</span><br><span class="line">print(e)</span><br><span class="line"></span><br><span class="line"><span class="comment"># 输出</span></span><br><span class="line">&#123;<span class="string">'a'</span>: <span class="number">1</span>, <span class="number">1</span>: <span class="number">2</span>, <span class="number">3</span>: <span class="string">'b'</span>&#125;</span><br><span class="line">&#123;<span class="string">'a'</span>: <span class="string">'b'</span>, <span class="number">1</span>: <span class="number">2</span>, <span class="number">3</span>: <span class="string">'c'</span>&#125;</span><br><span class="line">&#123;<span class="string">'a'</span>: <span class="number">1</span>, <span class="string">'b'</span>: <span class="number">3</span>&#125;</span><br><span class="line">&#123;<span class="string">'a'</span>: <span class="number">1</span>, <span class="string">'b'</span>: <span class="number">2</span>, <span class="string">'c'</span>: <span class="number">3</span>&#125;</span><br><span class="line">&#123;<span class="string">'a'</span>: <span class="number">2</span>, <span class="number">1</span>: <span class="string">'c'</span>, <span class="string">'b'</span>: <span class="number">3</span>&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment"># 通过类似于列表生成的方法生成字典</span></span><br><span class="line">l = dict((k, v) <span class="keyword">for</span> k,v <span class="keyword">in</span> enumerate([<span class="string">'a'</span>,<span class="string">'b'</span>,<span class="string">'c'</span>,<span class="string">'d'</span>]))</span><br><span class="line">print(l)</span><br></pre></td></tr></table></figure>
</li>
</ol>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/Python/" rel="tag"><i class="fa fa-tag"></i> Python</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/C++学习笔记.html" rel="prev" title="C++学习笔记">
                C++学习笔记 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
      <div id="lv-container" data-id="city" data-uid="MTAyMC8zNTkwMi8xMjQzOA=="></div>
    </div>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>


  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="/images/avatar.png"
                alt="David" />
            
              <p class="site-author-name" itemprop="name">David</p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">9</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">9</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">13</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          
            <div class="feed-link motion-element">
              <a href="/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="https://github.com/2033329616" target="_blank" title="GitHub">
                      
                        <i class="fa fa-fw fa-github"></i>GitHub</a>
                  </span>
                
            </div>
          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-3"><a class="nav-link" href="#1-python里args和-kwargs的用法"><span class="nav-number">1.</span> <span class="nav-text">1. python里args和*kwargs的用法</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2-python对txt文件的操作"><span class="nav-number">2.</span> <span class="nav-text">2.python对txt文件的操作</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3-python函数shutil，实现文件的复制"><span class="nav-number">3.</span> <span class="nav-text">3.python函数shutil，实现文件的复制</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#4-python实现读取文件夹里文件名功能"><span class="nav-number">4.</span> <span class="nav-text">4.python实现读取文件夹里文件名功能</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#5-python新建字典"><span class="nav-number">5.</span> <span class="nav-text">5.python新建字典</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      


      
        <script type="text/javascript" charset="utf-8" src="/js/tagcloud.js"></script>
        <script type="text/javascript" charset="utf-8" src="/js/tagcanvas.js"></script>
          <div class="widget-wrap">
            <h3 class="widget-title">Tag Cloud</h3>
          <div id="myCanvasContainer" class="widget tagcloud">
                <canvas width="250" height="250" id="resCanvas" style="width=100%">
                        <ul class="tag-list"><li class="tag-list-item"><a class="tag-list-link" href="/tags/C/">C++</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/C-调用Python/">C++调用Python</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/Linux/">Linux</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/Python/">Python</a><span class="tag-list-count">2</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/dlib/">dlib</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/docker/">docker</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/fopen/">fopen</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/matlab/">matlab</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/opencv/">opencv</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/sublime配置/">sublime配置</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/ubuntu系统/">ubuntu系统</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/日积月累/">日积月累</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/模型训练/">模型训练</a><span class="tag-list-count">1</span></li></ul>
                </canvas>
          </div>
          </div>
      
     

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2018</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">David</span>

  
</div>


  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Mist</a> v5.1.4</div>




        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  
    <script type="text/javascript">
      (function(d, s) {
        var j, e = d.getElementsByTagName(s)[0];
        if (typeof LivereTower === 'function') { return; }
        j = d.createElement(s);
        j.src = 'https://cdn-city.livere.com/js/embed.dist.js';
        j.async = true;
        e.parentNode.insertBefore(j, e);
      })(document, 'script');
    </script>
  












  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.4.js"></script>
  <script>AV.initialize("uUlSz2KUEfGIAPDphtd2ozjs-gzGzoHsz", "J8xwiak1VoyTejAmJWLtp2RT");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for(var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if( countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            counter.save(null, {
              success: function(counter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.get('time'));
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            var newcounter = new Counter();
            /* Set ACL */
            var acl = new AV.ACL();
            acl.setPublicReadAccess(true);
            acl.setPublicWriteAccess(true);
            newcounter.setACL(acl);
            /* End Set ACL */
            newcounter.set("title", title);
            newcounter.set("url", url);
            newcounter.set("time", 1);
            newcounter.save(null, {
              success: function(newcounter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(newcounter.get('time'));
              },
              error: function(newcounter, error) {
                console.log('Failed to create');
              }
            });
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script>



  

  
<script>
(function(){
    var bp = document.createElement('script');
    var curProtocol = window.location.protocol.split(':')[0];
    if (curProtocol === 'https') {
        bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';        
    }
    else {
        bp.src = 'http://push.zhanzhang.baidu.com/push.js';
    }
    var s = document.getElementsByTagName("script")[0];
    s.parentNode.insertBefore(bp, s);
})();
</script><!-- hexo-inject:begin --><!-- hexo-inject:end -->


  
  

  
  


  

  

</body>
</html>
